<template >

    <div class="bgc">
        <div class="container">

    <!-- 添加返回按钮 -->
    <div class="back-button-container">
      <button class="back-button" @click="router.push('/Common-ai')">
        <i class="back-icon">←</i> 返回主页面
      </button>
    </div>


    <h1>字形检索工具</h1>

    <div class="input-section">
      <div class="input-methods">
        <div 
          class="input-method-btn" 
          :class="{ active: activeMethod === 'upload' }" 
          @click="activeMethod = 'upload'"
        >
          上传图片
        </div>
        <div 
          class="input-method-btn" 
          :class="{ active: activeMethod === 'paste' }" 
          @click="activeMethod = 'paste'"
        >
          从剪贴板粘贴
        </div>
        <div 
          class="input-method-btn" 
          :class="{ active: activeMethod === 'base64' }" 
          @click="activeMethod = 'base64'"
        >
          输入Base64
        </div>
      </div>

      <div v-if="activeMethod === 'upload'" class="input-method-content active">
        <div class="input-group">
          <label for="imageFile">选择图片文件:</label>
            <div class="custom-upload">
                 <button class="custom-btn" @click="openFileDialog">选择文件</button>
                <span class="file-info">{{ selectedFileName || '未选择任何文件' }}</span>
              </div>
                 <input 
                    type="file" 
                    id="imageFile" 
                    accept="image/*" 
                   @change="handleFileChange"
                    style="display: none;"
            >
        </div>
      </div>

      <div v-if="activeMethod === 'paste'" class="input-method-content active">
        <div class="input-group">
          <label for="pasteArea">粘贴图片区域:</label>
          <div 
            id="pasteArea" 
            @click="pasteAreaFocus"
            @paste="handlePaste"
            :style="{ 
              border: '2px dashed #bdc3c7', 
              padding: '20px', 
              textAlign: 'center', 
              cursor: 'pointer', 
              minHeight: '180px', 
              display: 'flex', 
              flexDirection: 'column', 
              justifyContent: 'center', 
              alignItems: 'center'
            }"
          >
            <p>请在此区域粘贴图片 (Ctrl+V 或 Command+V)</p>
            <p class="paste-instruction">可以从截图工具、Word文档或其他来源复制图片后粘贴到这里</p>
          </div>
        </div>
      </div>

      <div v-if="activeMethod === 'base64'" class="input-method-content active">
        <div class="input-group">
          <label for="imageBase64">输入Base64编码:</label>
          <textarea 
            id="imageBase64" 
            placeholder="输入图片的Base64编码"
            v-model="base64Data"
            @input="handleBase64Change"
          ></textarea>
        </div>
      </div>

      <div class="preview">
        <h3>图片预览</h3>
        <img 
          id="imagePreview" 
          :src="previewImage" 
          :style="{ display: previewImage ? 'block' : 'none', maxWidth: '300px', maxHeight: '300px', border: '1px solid #ddd', borderRadius: '4px' }"
        >
      </div>

      <div class="button-group">
        <button id="searchBtn" @click="handleSearch">检索字形</button>
        <button id="resetBtn" @click="handleReset">重置</button>
      </div>

      <div class="error" id="errorMsg" v-if="errorMessage" :style="{ display: 'block' }">
        {{ errorMessage }}
      </div>
    </div>

    <div class="loading" id="loading" v-if="isLoading">
      <div class="spinner"></div>
      <p>正在检索中，请稍候...</p>
    </div>

    <div class="results" v-show="results.length > 0">
      <h2>检索结果</h2>
      <div id="resultCount" v-if="results.length > 0">
        <p>共找到 {{ results.length }} 个匹配结果</p>
      </div>
      <div id="resultCount" v-else-if="endloading&&!isLoading && results.length === 0">
        <p>未找到匹配结果</p>
      </div>
      <div class="result-grid" id="resultGrid">
        <div class="result-item" v-for="(item, index) in results" :key="index" @mouseenter="hoverItem = index" @mouseleave="hoverItem = -1">
          <img 
            :src="item.imageUrl" 
            :alt="item.bookName" 
            class="result-image"
            :style="{ 
              width: '100%', 
              height: '150px', 
              objectFit: 'contain', 
              marginBottom: '10px', 
              border: '1px solid #eee', 
              borderRadius: '3px',
              transform: hoverItem === index ? 'translateY(-5px)' : 'none',
              boxShadow: hoverItem === index ? '0 5px 15px rgba(0, 0, 0, 0.1)' : 'none',
              transition: 'transform 0.3s, boxShadow 0.3s'
            }"
            @error="item.imageUrl = fallbackImage"
          >
          <div class="result-info">
            <div class="result-book">{{ item.bookName }}</div>
            <div>片号: {{ item.bookItemId }}</div>
            <div>相似度: {{ item.similarity.toFixed(3) }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
    </div>
  
</template>

<script setup>
import { ref, onMounted } from 'vue';
import{ useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores'
// 路由
const router = useRouter();

// 状态管理
const activeMethod = ref('upload');
const base64Data = ref('');
const previewImage = ref('');
const isLoading = ref(false);
const results = ref([]);
const errorMessage = ref('');
const hoverItem = ref(-1);
const fallbackImage = 'data:image/svg+xml;charset=UTF-8,%3Csvg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"100\" viewBox=\"0 0 100 100\"%3E%3Crect width=\"100\" height=\"100\" fill=\"%23eee\" /%3E%3Ctext x=\"50\" y=\"50\" font-family=\"Arial\" font-size=\"10\" text-anchor=\"middle\" dominant-baseline=\"middle\" fill=\"%23999\"%3E图片加载失败%3C/text%3E%3C/svg%3E';
const endloading = ref(false);
const baseUrl = import.meta.env.VITE_BASE_URL

const selectedFileName = ref(''); // 用于显示文件名

// 点击自定义按钮，触发原生文件框
const openFileDialog = () => {
  document.getElementById('imageFile').click();
};
// 文件上传处理
const handleFileChange = (e) => {
  const file = e.target.files[0];
  console.log('file是',file)
  if (file) {
     selectedFileName.value = file.name; // 显示文件名
    const reader = new FileReader();
    reader.onload = (event) => {
      base64Data.value = event.target.result.split(',')[1];
      previewImage.value = event.target.result;
      errorMessage.value = '';
    };
    reader.readAsDataURL(file);
  }
};

// Base64输入变化处理
const handleBase64Change = () => {
  if (base64Data.value) {
    previewImage.value = `data:image/png;base64,${base64Data.value}`;
    errorMessage.value = '';
  } else {
    previewImage.value = '';
  }
};

// 剪贴板粘贴处理
const pasteAreaFocus = () => {
  document.getElementById('pasteArea').focus();
};

const handlePaste = async (e) => {

  e.preventDefault();
  const items = e.clipboardData.items;
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image')!== -1) {
      const blob = items[i].getAsFile();
      const reader = new FileReader();

      reader.onload = (event) => {
        const base64Str = event.target.result.split(',')[1];
        base64Data.value = base64Str;
        previewImage.value = event.target.result;
        errorMessage.value = '';

        // 切换到Base64标签
        activeMethod.value = 'base64';
      };

      reader.readAsDataURL(blob);
      return;
    }
  }

  errorMessage.value = '剪贴板中没有找到图片，请复制图片后再尝试粘贴';
  // 调用错误信息消失函数
  errorAutoHide();
};

// 检索处理
// 假设从某处获取用户身份令牌，这里先模拟定义，实际需按真实逻辑获取
const userStore= useUserStore();

const token = userStore.token; 

const handleSearch = async () => {
    if (!base64Data.value.trim()) {
        errorMessage.value = '请上传图片或输入Base64编码';
        errorAutoHide();
        return;
    }

    isLoading.value = true;
    results.value = [];
    errorMessage.value = '';

    try {
        const dataBase64Data = `data:image/png;base64,${base64Data.value}`;
        
        // 接口请求路径，按文档是 /glyph/matching
        const apiUrl = `${baseUrl}/glyph/matching`; 
        
         // 创建FormData对象
            const formData = new FormData();

            // 添加表单字段
                formData.append('image_base64', dataBase64Data);
                formData.append('image_url', '');
                  formData.append('image_path', '');

           // 发送请求
                const response = await fetch(apiUrl, {
                  method: "POST",
                    headers: {
                        Authorization: `Bearer ${token}`,
                      },
                   body: formData
                  });

                 if (!response.ok) {
            // 若响应状态码不是 2xx，尝试解析响应体看具体错误信息
            const errorBody = await response.json();
            throw new Error(`网络响应不正常，服务端返回：${errorBody.message || '无具体信息'}`);
        }
           
        const data = await response.json();
     
        // 按文档响应结构处理，文档里成功响应是 data.results 直接是结果数组
        if (data && data.code === 200 && data.data && data.data.results) { 
            await processResults(data.data.results);
        } else if (data && data.code === 400) {
            errorMessage.value = `客户端错误：${data.message || '缺少必要参数'}`;
            errorAutoHide();
        } else if (data && data.code === 500) {
            errorMessage.value = `服务端错误：${data.message || '外部API调用失败'}`;
            errorAutoHide();
        } else {
            errorMessage.value = '未找到匹配结果或数据结构不符合预期';
            errorAutoHide();
        }
    } catch (error) {
        errorMessage.value = `检索失败: ${error.message}`;
        errorAutoHide();
    } finally {
        isLoading.value = false;
        endloading.value = true;
    }
};

// 处理结果数据
const processResults = async (rawResults) => {
  const processedResults = [];

  for (const item of rawResults) {


    processedResults.push({
      bookName: item.bookName,
      bookItemId: item.bookItemId,
      similarity: item.similarity,
      imageUrl: item.imageUrl
    });
  }

  results.value = processedResults;
};


// 重置功能
const handleReset = () => {
  base64Data.value = '';
  previewImage.value = '';
  results.value = [];
  errorMessage.value = '';
   selectedFileName.value = '';
};

// 错误信息自动消失函数
const errorAutoHide = () => {
  setTimeout(() => {
    errorMessage.value = '';
  }, 2000);
};


</script>


<style scoped> 

/* 添加返回按钮样式 */

.custom-upload {
  display: flex;
  align-items: center;
  gap: 8px;

  /* 边框 */
  border: 1.5px solid #d9b98b; 
  /* 背景颜色，可根据需求调整 */
  background-color: #f9f5eb; 
  /* 内边距 */
  padding: 8px 12px; 
  /* 圆角，让外观更柔和，和截图风格适配 */
  border-radius: 6px; 
  /* 让光标看起来可点击，提升交互感 */
  cursor: pointer; 
}

.custom-btn {
  background-color: #f2e8d8;
  color: #8b5a2b;
  border: 1px solid #e6d2b8;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.custom-btn:hover {
  background-color: #e6d2b8;
  border-color: #d9b98b;
  color: #7a4f20;
}

.file-info {
  color: #664422;
  font-size: 14px;
}

.back-button-container {
  margin-bottom: 15px;
  text-align: left;
}

.back-button {
  background-color: #f2e8d8;
  color: #8b5a2b;
  border: 1px solid #e6d2b8;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.back-button:hover {
  background-color: #e6d2b8;
  border-color: #d9b98b;
  color: #7a4f20;
  transform: translateX(-2px);
}

.back-icon {
  font-size: 16px;
}
/* 
.bgc {
  background-color: #f9f5eb;
width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
} */

/* 修改图片预览样式 */
.preview-image {
  width: 100%;
  max-width: 100%;
  height: auto;
  border-radius: 8px;
}
 


/* 基础容器布局 */
.container {
  max-width: 1200px;
  margin: 40px auto 30px;
 background-color: #f9f5eb;
  padding: 30px 20px;
  border-radius: 12px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.05);
  min-height: calc(100vh - 150px);
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  color: #8b5a2b;
  font-size: 28px;
  margin-bottom: 12px;
  font-weight: 600;
}

/* 输入区整体样式 */
.input-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-bottom: 20px;
  padding: 25px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  flex: 1;
}

/* 输入方式切换按钮组 */
.input-methods {
  display: flex;
  gap: 12px;
  margin-bottom: 15px;
  flex-wrap: wrap;
  justify-content: center;
}

.input-method-btn {
  flex: 1;
  max-width: 200px;
  padding: 12px 20px;
  background-color: #f2e8d8;
  border: 1px solid #e6d2b8;
  border-radius: 6px;
  cursor: pointer;
  text-align: center;
  color: #8b5a2b;
  font-size: 16px;
  transition: all 0.3s ease;
}

.input-method-btn:hover {
  background-color: #e6d2b8;
  border-color: #d9b98b;
  color: #7a4f20;
}

.input-method-btn.active {
  background-color: #8b5a2b;
  color: #fff;
  border-color: #8b5a2b;
}

/* 输入方式内容区（上传/粘贴/Base64） */
.input-method-content {
  display: none;
  flex-direction: column;
  gap: 15px;
}
.input-method-content.active {
  display: flex;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

label {
  font-weight: 500;
  color: #8b5a2b;
  font-size: 14px;
}



/* 优化文件上传按钮容器 */
.input-group input[type="file"] {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  /* 让输入框更协调 */
  padding: 8px 10px;
  border: 1px solid #e6d2b8;
  border-radius: 6px;
  background-color: #fffbf7;
  color: #664422;
  font-size: 14px;
  /* 排版优化 */
  display: flex;
  align-items: center;
  gap: 8px;
  transition: border-color 0.3s ease;
}

/* 自定义按钮外观 */
.input-group input[type="file"]::file-selector-button {
  background: linear-gradient(135deg, #f2e8d8 0%, #efe2cc 100%); /* 渐变背景 */
  border: 1px solid #e6d2b8;
  color: #8b5a2b;
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
  cursor: pointer;
  /* 增加立体阴影 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  /* 让按钮更有层次 */
  position: relative;
  z-index: 1;
}

/* 鼠标悬浮效果 */
.input-group input[type="file"]::file-selector-button:hover {
  background: linear-gradient(135deg, #e6d2b8 0%, #d9c6a8 100%); /* 加深渐变 */
  border-color: #d9b98b;
  color: #7a4f20;
  /* 提升阴影层次 */
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.08);
  transform: translateY(-1px); /* 轻微上浮 */
}

/* 按钮点击反馈 */
.input-group input[type="file"]::file-selector-button:active {
  transform: translateY(1px); /* 点击下沉 */
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}


textarea,
input[type="file"] {
  padding: 8px 10px;
  border: 1px solid #e6d2b8;
  border-radius: 6px;
  font-size: 14px;
  color: #664422;
  background-color: #fffbf7;
  transition: border-color 0.3s;
}

textarea:focus,
input[type="file"]:focus {
  outline: none;
  border-color: #d9b98b;
}

textarea {
  min-height: 100px;
  resize: vertical;
}

/* 粘贴区域特殊样式 */
#pasteArea {
  border: 2px dashed #e6d2b8;
  padding: 35px;
  text-align: center;
  cursor: pointer;
  min-height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 6px;
  transition: border-color 0.3s;
}
#pasteArea:hover {
  border-color: #d9b98b;
}

.paste-instruction {
  font-size: 12px;
  color: #996633;
  margin-top: 8px;
  line-height: 1.4;
}

/* 图片预览区 */
.preview {
  text-align: center;
  margin-top: 20px;
  margin-bottom: 10px;
}

.preview h3 {
  color: #8b5a2b;
  margin-bottom: 15px;
}

#imagePreview {
  max-width: 350px;
  max-height: 350px;
  border: 1px solid #e6d2b8;
  border-radius: 6px;
  display: none;
  margin: 0 auto;
  padding: 10px;
  background-color: #fff;
}
#imagePreview[src] {
  display: block;
}

/* 按钮组（检索 + 重置） */
.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
}

/* 按钮通用样式 */
button {
  background-color: #8b5a2b;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 15px;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #7a4f20;
}

button:disabled {
  background-color: #c9b090;
  cursor: not-allowed;
}

/* 错误提示 */
.error {
  color: #c0392b;
  padding: 12px;
  background-color: #fce8e6;
  border-radius: 6px;
  margin-top: 15px;
  font-size: 14px;
  display: none;
  text-align: center;
}
.error.active {
  display: block;
}

/* 加载状态 */
.loading {
  text-align: center;
  padding: 30px;
  margin: 20px 0;
}
.loading.active {
  display: block;
}

.spinner {
  border: 5px solid rgba(139, 90, 43, 0.1);
  border-radius: 50%;
  border-top: 5px solid #8b5a2b;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 0 auto 15px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 检索结果区 */
.results {
  margin-top: 30px;
  background-color: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
  flex: 2;
}

.results h2 {
  color: #8b5a2b;
  font-size: 20px;
  margin-bottom: 25px;
  font-weight: 600;
  text-align: center;
}

.result-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 25px;
  margin-top: 25px;
}

.result-item {
  border: 1px solid #e6d2b8;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  background-color: #fffbf7;
  transition: transform 0.3s, box-shadow 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.result-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.07);
}

.result-image {
  width: 100%;
  height: 160px;
  object-fit: contain;
  border: 1px solid #e6d2b8;
  border-radius: 4px;
  margin-bottom: 15px;
  padding: 5px;
  background-color: #fff;
}

.result-info {
  font-size: 14px;
  color: #664422;
  line-height: 1.8;
  margin-top: auto;
}

.result-book {
  font-weight: 600;
  color: #8b5a2b;
  margin-bottom: 8px;
  display: block;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .container {
    margin: 20px;
    max-height: calc(100vh - 40px);
  }
  .input-methods {
    flex-direction: column;
  }
  .input-method-btn {
    margin-bottom: 5px;
  }
  .result-grid {
    grid-template-columns: 1fr;
  }
} 
</style>